/**
 * Created by Dell on 2017/4/26.
 */
'use strict';
const pg = require('../lib/pgClient');
const log = require('log4js').getLogger("models/console");
/**
 * 后台系统首页数据统计
 * @param params
 * @param callback
 */
const home_sql1 = 'SELECT count(*) FROM users WHERE bindtine >= $1';//新增用户数
const home_sql2 = 'SELECT count(*) FROM picture WHERE pushtime >= $1';//新政图片数
const home_sql3 = 'SELECT count(*) FROM article WHERE createtime >= $1';//新增文章数
const home_sql4 = 'SELECT count(*) FROM picture';//总用户数
exports.home_data = function(params, callback){
    let info = {
        new_user:0,//新增用户数
        new_picture:0,//新增图片数
        new_article:0,//新增文章数
        totle_user:0//总用户数
    };
    pg.query(home_sql1, params, function(err, result){//查新增用户
        if(err){
            callback (err, null);
        }else {
            info.new_user = result.rows[0].count;//新用户数（处理数据）
            pg.query(home_sql2, params, function(err, result){//查新增图片
                if(err){
                    callback (err, null);
                }else {
                    info.new_picture = result.rows[0].count;//新图片数（处理数据）
                    pg.query(home_sql3, params, function(err, result){//查新增文章
                        if(err){
                            callback (err, null);
                        }else {
                            info.new_article = result.rows[0].count;//新文章数（处理数据）
                            pg.query(home_sql4, [], function(err, result){//查总用户
                                if(err){
                                    callback (err, null);
                                }else {
                                    info.totle_user = result.rows[0].count;//总用户数（处理数据）
                                    callback (err, info);//将所有数据返回去
                                }
                            });
                        }
                    });
                }
            });
        }
    });
};
/**
 * 后台系统首页中的图片数据
 * 今日是不稳定的，只能统计到今日之前的数据
 * @param callback
 */
const picture_sql = 'SELECT count(*) FROM picture WHERE pushtime BETWEEN $1 AND $2';//统计在$1和$2时间段之间的
exports.home_picture = function(callback){
    let date = new Date();
    let nowYear = date.getFullYear();
    let nowMonth = date.getMonth() + 1;  //注意getMonth从0开始
    let nowDay = date.getDate();
    let d1=nowYear + ',' + nowMonth + ',' + nowDay ;   //将当前日期的年月日整合到d中
    let d2=new Date(new Date(d1).getTime() - 86400000);   //将当前日期的年月日整合到d中
    let d3=new Date(new Date(d1).getTime() - (86400000*2));   //将当前日期的年月日整合到d中
    let d4=new Date(new Date(d1).getTime() - (86400000*7));   //将当前日期的年月日整合到d中
    let d5=new Date(new Date(d1).getTime() - (86400000*30));   //将当前日期的年月日整合到d中
    let date1 = new Date(d1);   //获取当日00：00：00的标准时间
    let date2 = new Date(d2);   //获取昨日00：00：00的标准时间
    let date3 = new Date(d3);   //获取前天00：00：00的标准时间
    let date4 = new Date(d4);   //获取一周前00：00：00的标准时间
    let date5 = new Date(d5);   //获取30天前00：00：00的标准时间
    const params1 = [//昨天一天
        date2,
        date1
    ];
    const params2 = [//前天一天
        date3,
        date2
    ];
    const params3 = [//前7天
        date4,
        date1
    ];
    const params4 = [//前30天
        date5,
        date1
    ];
    let info = {
        last_day:0,
        tow_days_ago:0,
        a_week_ago:0,
        th_days_ago:0
    }
    pg.query(picture_sql, params1, function(err, result){//昨天
        if(err){
            callback (err, null);
        }else {
            info.last_day = result.rows[0].count;//昨天数据
            pg.query(picture_sql, params2, function(err, result){//2天前
                if(err){
                    callback (err, null);
                }else {
                    info.tow_days_ago = result.rows[0].count;//2天前数据
                    pg.query(picture_sql, params3, function(err, result){//一周
                        if(err){
                            callback (err, null);
                        }else {
                            info.a_week_ago = result.rows[0].count;//一周数据
                            pg.query(picture_sql, params4, function(err, result){//一个月
                                if(err){
                                    callback (err, null);
                                }else {
                                    info.th_days_ago = result.rows[0].count;//一个月数据
                                    callback (err, info);//返回数据集
                                }
                            });
                        }
                    });
                }
            });
        }
    });
};
/**
 * 后台系统首页中的用户数据
 * 今日是不稳定的，只能统计到今日之前的数据
 * @param callback
 */
const users_sql = 'SELECT count(*) FROM users WHERE bindtine BETWEEN $1 AND $2';//统计在$1和$2时间段之间的
exports.home_users = function(callback){
    let date = new Date();
    let nowYear = date.getFullYear();
    let nowMonth = date.getMonth() + 1;  //注意getMonth从0开始
    let nowDay = date.getDate();
    let d1=nowYear + ',' + nowMonth + ',' + nowDay ;   //将当前日期的年月日整合到d中
    let d2=new Date(new Date(d1).getTime() - 86400000);   //将当前日期的年月日整合到d中
    let d3=new Date(new Date(d1).getTime() - (86400000*2));   //将当前日期的年月日整合到d中
    let d4=new Date(new Date(d1).getTime() - (86400000*7));   //将当前日期的年月日整合到d中
    let d5=new Date(new Date(d1).getTime() - (86400000*30));   //将当前日期的年月日整合到d中
    let date1 = new Date(d1);   //获取当日00：00：00的标准时间
    let date2 = new Date(d2);   //获取昨日00：00：00的标准时间
    let date3 = new Date(d3);   //获取前天00：00：00的标准时间
    let date4 = new Date(d4);   //获取一周前00：00：00的标准时间
    let date5 = new Date(d5);   //获取30天前00：00：00的标准时间
    const params1 = [//昨天一天
        date2,
        date1
    ];
    const params2 = [//前天一天
        date3,
        date2
    ];
    const params3 = [//前7天
        date4,
        date1
    ];
    const params4 = [//前30天
        date5,
        date1
    ];
    let info = {
        last_day:0,
        tow_days_ago:0,
        a_week_ago:0,
        th_days_ago:0
    }
    pg.query(users_sql, params1, function(err, result){//昨天
        if(err){
            callback (err, null);
        }else {
            info.last_day = result.rows[0].count;//昨天数据
            pg.query(users_sql, params2, function(err, result){//2天前
                if(err){
                    callback (err, null);
                }else {
                    info.tow_days_ago = result.rows[0].count;//2天前数据
                    pg.query(users_sql, params3, function(err, result){//一周
                        if(err){
                            callback (err, null);
                        }else {
                            info.a_week_ago = result.rows[0].count;//一周数据
                            pg.query(users_sql, params4, function(err, result){//一个月
                                if(err){
                                    callback (err, null);
                                }else {
                                    info.th_days_ago = result.rows[0].count;//一个月数据
                                    callback (err, info);//返回数据集
                                }
                            });
                        }
                    });
                }
            });
        }
    });
};
/**
 * 后台系统首页中的活跃分类数据
 * @param req
 * @param res
 */
exports.top_type = function(callback){
    let date = new Date();
    let nowYear = date.getFullYear();
    let nowMonth = date.getMonth() + 1;  //注意getMonth从0开始
    let nowDay = date.getDate();
    let d1=nowYear + ',' + nowMonth + ',' + nowDay ;   //将当前日期的年月日整合到d中
    let date1 = new Date(d1);   //获取当日00：00：00的标准时间

    let sql = 'SELECT t.typename, count(p.*) as number FROM type t, picture p WHERE t.id = p.tid AND p.pushtime > $1 GROUP BY t.typename ORDER BY number DESC limit 5';
    pg.query(sql, [date1], function (err,result){
        if(err){
            return callback(err,null);
        }else{
            return callback(err,result);
        }
    });
};
/**
 * 后台系统首页中的活跃分类数据
 * @param req
 * @param res
 */
exports.top_users = function(callback){
    let date = new Date();
    let nowYear = date.getFullYear();
    let nowMonth = date.getMonth() + 1;  //注意getMonth从0开始
    let nowDay = date.getDate();
    let d1=nowYear + ',' + nowMonth + ',' + nowDay ;   //将当前日期的年月日整合到d中
    let date1 = new Date(d1);   //获取当日00：00：00的标准时间
    const params = [
        date1
    ]
    let sql = 'SELECT u.headurl, p.username, count(p.*) as number FROM users u, picture p WHERE u.id = p.author AND p.pushtime > $1 GROUP BY u.headurl, p.username, p.author ORDER BY number DESC limit 5';
    pg.query(sql, params, function (err,result){
        if(err){
            return callback(err,null);
        }else{
            return callback(err,result);
        }
    });
};


/**
 * 控制台中的折线图
 * @param params
 * @param args
 * @param callback
 */
exports.user_line_chart = function(params, args, callback) {
    // let sql1 = 'SELECT id FROM users ORDER BY bindtine ASC';
    let sql = 'SELECT id, bindtine FROM users ORDER BY bindtine ASC';
        pg.query(sql , [], function(err,result){
            if(err){
                return callback(err,null);
            }else{
                let users = result.rows;
                let least_time = result.rows[0].bindtine;
                let infos = [];
                    users.forEach(function(one_user) {
                        if (args.date == 'year') {
                            let Year = one_user.bindtine.getFullYear();
                            let len = infos.length;
                            let a = 0;
                            if (len == 0) {
                                infos.push({time: Year, num: 1});
                            } else {
                                for (var i = 0; i < len; i++) {
                                    if (infos[i].time == Year) {
                                        infos[i].num++;
                                        a++;
                                        break;
                                    }
                                }
                                if (a == 0) {
                                    infos.push({time: Year, num: 1});
                                }
                            }
                        } else if (args.date == 'month') {
                            let the_Yesr = one_user.bindtine.getFullYear();
                            let the_Month = one_user.bindtine.getMonth() + 1;
                            let Month = the_Yesr + '-' + the_Month;
                            let len = infos.length;
                            let a = 0;
                            if (len == 0) {
                                infos.push({time: Month, num: 1});
                            } else {
                                for (var i = 0; i < len; i++) {
                                    if (infos[i].time == Month) {
                                        infos[i].num++;
                                        a = 1;
                                        break;
                                    }
                                }
                                if (a == 0) {
                                    infos.push({time: Month, num: 1});
                                }
                            }

                        } else {
                            let the_Yesr = one_user.bindtine.getFullYear();
                            let the_Month = one_user.bindtine.getMonth() + 1;
                            let the_Day = one_user.bindtine.getDate();
                            let Day = the_Yesr + '-' + the_Month + '-' + the_Day
                            let len = infos.length;
                            let a = 0;
                            if (len == 0) {
                                infos.push({time: Day, num: 1});
                            } else {
                                for (var i = 0; i < len; i++) {
                                    if (infos[i].time == Day) {
                                        infos[i].num++;
                                        a = 1;
                                        break;
                                    }
                                }
                                if (a == 0) {
                                    infos.push({time: Day, num: 1});
                                }
                            }
                        }

                    })

            let leng = infos.length;
            infos[leng]={
                least_time:least_time?least_time:null
            }
            return callback(err,infos);
            }
        });
};


/**
 * 控制台中的图片折线图
 * @param params
 * @param args
 * @param callback
 */
exports.picture_line_chart = function(params, args, callback) {
    // let sql1 = 'SELECT id FROM users ORDER BY bindtine ASC';
    let sql = 'SELECT id, pushtime FROM picture WHERE del = $1 ORDER BY pushtime ASC';
        pg.query(sql , [1], function(err,result){
            if(err){
                return callback(err,null);
            }else{
                let pictures = result.rows;
                let least_time = result.rows[0].pushtime;
                let infos = [];
                pictures.forEach(function(one_picture) {
                        if (args.date == 'year') {
                            let Year = one_picture.pushtime.getFullYear();
                            let len = infos.length;
                            let a = 0;
                            if (len == 0) {
                                infos.push({time: Year, num: 1});
                            } else {
                                for (var i = 0; i < len; i++) {
                                    if (infos[i].time == Year) {
                                        infos[i].num++;
                                        a++;
                                        break;
                                    }
                                }
                                if (a == 0) {
                                    infos.push({time: Year, num: 1});
                                }
                            }
                        } else if (args.date == 'month') {
                            let the_Yesr = one_picture.pushtime.getFullYear();
                            let the_Month = one_picture.pushtime.getMonth() + 1;
                            let Month = the_Yesr + '-' + the_Month;
                            let len = infos.length;
                            let a = 0;
                            if (len == 0) {
                                infos.push({time: Month, num: 1});
                            } else {
                                for (var i = 0; i < len; i++) {
                                    if (infos[i].time == Month) {
                                        infos[i].num++;
                                        a = 1;
                                        break;
                                    }
                                }
                                if (a == 0) {
                                    infos.push({time: Month, num: 1});
                                }
                            }

                        } else {
                            let the_Yesr = one_picture.pushtime.getFullYear();
                            let the_Month = one_picture.pushtime.getMonth() + 1;
                            let the_Day = one_picture.pushtime.getDate();
                            let Day = the_Yesr + '-' + the_Month + '-' + the_Day
                            let len = infos.length;
                            let a = 0;
                            if (len == 0) {
                                infos.push({time: Day, num: 1});
                            } else {
                                for (var i = 0; i < len; i++) {
                                    if (infos[i].time == Day) {
                                        infos[i].num++;
                                        a = 1;
                                        break;
                                    }
                                }
                                if (a == 0) {
                                    infos.push({time: Day, num: 1});
                                }
                            }
                        }

                    })

            let leng = infos.length;
            infos[leng]={
                least_time:least_time?least_time:null
            }
            return callback(err,infos);
            }
        });
};
